package org.example.SqlSessionUtil;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
/*
* 封装SqlSessionUtil类  这样更好调用
*
* */
public class SqlSessionUtil {
    //被static修饰才能被静态代码块访问
    //成员变量整个类都可以访问到 在创建sqlsession对象时需要访问
   private static SqlSessionFactory sessionFactory;
    //读取配置文件
    static {
        InputStream is = null;
        try {
              is = Resources.getResourceAsStream("mybatis.xml");
            SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
            //构建者建造了工厂
            sessionFactory = builder.build(is);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    //获得SqlSession对象
    public  static SqlSession getSqlSession(){
        //工厂创建对象
        SqlSession sqlSession = sessionFactory.openSession();
        return sqlSession;
    }
    public static void closeSqlSession(SqlSession sqlSession){
        //关闭sqlsession
        if (sqlSession != null){
            sqlSession.close();
        }
    }
}
